#include "timer.h"

double CycleTimer::cpu_period = -1.0;


#ifdef _WIN32
int gettimeofday(struct timeval *tv, struct timezone *tz)
{
  // Define a structure to receive the current Windows filetime
  FILETIME ft;
  // Initialize the present time to 0 and the timezone to UTC
  unsigned __int64 tmpres = 0;
  static int tzflag = 0;

  if (NULL != tv){
    GetSystemTimeAsFileTime(&ft);

    // The GetSystemTimeAsFileTime returns the number of 100 nanosecond 
    // intervals since Jan 1, 1601 in a structure. Copy the high bits to 
    // the 64 bit tmpres, shift it left by 32 then or in the low 32 bits.
    tmpres |= ft.dwHighDateTime;
    tmpres <<= 32;
    tmpres |= ft.dwLowDateTime;

    // Convert to microseconds by dividing by 10
    tmpres /= 10;

    // The Unix epoch starts on Jan 1 1970.  Need to subtract the difference 
    // in seconds from Jan 1 1601.
    tmpres -= DELTA_EPOCH_IN_MICROSECS;

    // Finally change microseconds to seconds and place in the seconds value. 
    // The modulus picks up the microseconds.
    tv->tv_sec = (long)(tmpres / 1000000UL);
    tv->tv_usec = (long)(tmpres % 1000000UL);
  }

  if (NULL != tz)
  {
    /*
    // This code does not work!
    if (!tzflag)
    {
      _tzset();
      tzflag++;
    }

    // Adjust for the timezone west of Greenwich
    tz->tz_minuteswest = (*__timezone()) / 60;
    tz->tz_dsttime = _daylight;
    */
  }

  return 0;
}
#endif

double GetCPUClockRateMHz()
{
#ifdef linux
  static double mhz = 0.0;
  if(mhz > 0.0) return(mhz);

  FILE *in = fopen("/proc/cpuinfo","rt");
  const int length=64;
  char buf[length],*s;

  if(in){
    while(fgets(buf,length,in)){
      if(strncmp(buf,"cpu MHz",7) == 0){
        s = strchr(buf,':');
        if(*s) s++;
        mhz = atof(s);
      }
    }
    // while(!feof(in) && fscanf(in,"cpu MHz%*s:%lf\n",&mhz)!=1);
    fclose(in);
  }
  // printf("mhz=%f\n",mhz);
  return(mhz);
#endif

#ifdef Apertos
  // Return constant, since supercore Aibos and the SDR are 400MHz
  // should eventually figure out how to actually get this properly
  return(400);
#endif

  // default, fail
  return(0.0);
}

double GetCPUClockPeriod()
{
  static double period = 0.0;
  if(period != 0.0) return(period);

  period = 1E-6 / GetCPUClockRateMHz();
  return(period);
}
